//
//  SellerHomeCtr-cells.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/10/16.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import soapp

private var default_order = "desc"
protocol OrderMenuDelegate:NSObjectProtocol {
    func changeTheOrder(params:[String:Any])
    func changeTheFilter(params:[String:Any])
}


public class GoodsFilter {
    public var level1:String? = nil
    public var level2:String? = nil
    public var key:String? = nil
    
    public var values:[String:Any]{
        get{
            var _vs = [String:Any]()
            if let lever2 = self.level2
            {
                _vs["ccat_id"] = lever2
            }
            if let lever1 = self.level1
            {
                if lever1 == "全部".loc
                {
                    _vs.removeAll()
                }
                else{
                    _vs["cat_id"] = lever1
                }
            }
            return _vs
        }
    }
}

private let bar_height:CGFloat = 38

open class OrderMenu:JoView,CollectionVConfig{
    public var goodsFilter:GoodsFilter{
        get{
            return self.filter.goodsFilter
        }
    }
    
    weak var delegate:OrderMenuDelegate? = nil
    var sections:TP.section{
        get{
            let sec:TP.section = [
                menus
            ]
            return sec
        }
    }
    
    open var menus:[[String:Any]]{
        
        get{
            let icon = UIImage.imageWithColor(color:.clear)
            
            let ms = [
                [
                    "name":"商品分类".loc,"icon":#imageLiteral(resourceName: "sc_fl"),
                    "cellID":"cate",
                ],
                [
                    "name":"最新".loc,
                    "cellID":"new",
                    "order":"updatetime",
                    "selected":"YES"
                ],
                [
                    "name":"价格".loc,
                    "cellID":"price",
                    "order":"shop_price",
                    FK.value:default_order,
                    FK.defaultV:default_order,
                    "options":[
                        ["name":"升序".loc,"value":"desc"],
                        ["name":"降序".loc,"value":"asc"],
                    ],
                    "icon":UIImage(named:"sc_px") ?? icon,"icon_asc":UIImage(named:"sc_px") ?? icon,"icon_desc":UIImage(named:"sc_px2") ?? icon,
                    ],
                [
                    "name":"热度".loc,
                    "cellID":"hot",
                    "order":"click_count"
                ],
            ]
            return ms
        }
    }
    
    
    var selector:TP.selector =
        [
            "cellID<hot,new>":DescOrderKit.self,
            "cellID<price>":FullOrderKit.self,
            "cellID<cate>":FilterKit.self
//            "name<积分排序>":FullOrderKit.self,

    ]
    
    
    var collectionView:UICollectionView!
    var pageControl = UIPageControl()
    var flow = UICollectionViewFlowLayout()
    
    override open func addLayoutRules() {
        //        let lineV = UIView()
        //        addSubview(lineV)
        //        lineV.frame = [0,36,Swidth,3]
        //        lineV.backgroundColor = UIColor.table_bg_color
        self.frame = [0,0,Swidth,bar_height]
        
        self.collectionView = UICollectionView(frame: [0,0,Swidth,bar_height], collectionViewLayout: self.flow)
        addSubview(collectionView)
        collectionView.layoutMargins = UIEdgeInsets.zero
        self.flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.flow.scrollDirection = .horizontal
        flow.minimumInteritemSpacing = 0
        flow.minimumLineSpacing = 0
        collectionView.backgroundColor = .white
        self.configCollectionVs(collectionVs: collectionView)
        collectionView.load(sections: sections, selector: selector)
        backgroundColor = .white
    }
    
    
    
    public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        switch actionID {
        case "change":
            guard let list = DataNode<NSMutableArray>.path(node: "section0", collectionView.model) else {
                return
            }
            list.listObj({ (dict:NSMutableDictionary) in
                if dict["name",""] != model["name",""]
                {
                    dict[FK.selected] = FK.NO
                }else{
                    dict[FK.selected] = FK.YES
                }
            })
            collectionView.reloadData()
            var values = [String:Any]()
            values["order_key"] = model["order","time"]
            //            values["order_method"] = model["value",default_order]
            values["order_method"] = default_order
            
            self.delegate?.changeTheOrder(params: values)
            
        case "change_price_order":
            guard let list = DataNode<NSMutableArray>.path(node: "section0", collectionView.model) else {
                return
            }
            list.listObj({ (dict:NSMutableDictionary) in
                if dict["name",""] != model["name",""]
                {
                    dict[FK.selected] = FK.NO
                }else{
                    dict[FK.selected] = FK.YES
                }
            })
            collectionView.reloadData()
            var values = [String:Any]()
            values["order_key"] = model["order","shop_price"]
            values["order_method"] = model["value",default_order]
            self.delegate?.changeTheOrder(params: values)
            
        default:
            guard let list = DataNode<NSMutableArray>.path(node: "section0", collectionView.model) else {
                return
            }
            list.listObj({ (dict:NSMutableDictionary) in
                if dict["name",""] != model["name",""]
                {
                    dict[FK.selected] = FK.NO
                }else{
                    dict[FK.selected] = FK.YES
                }
            })
            collectionView.reloadData()
            
            weak var wself = self
            self.filter.confirmFilter = {
                if let ctr = wself?.delegate as? SellerHomeCtr
                {
                    ctr.goodsFilter = $0
                }
                wself?.delegate?.changeTheFilter(params: $0.values)
            }
            
            
            guard let ViewCtr = self.delegate as? UIViewController else {
                return
            }
            ViewCtr.present(self.filter, animated: false, completion: nil)
            break
        }
    }
    
    var _filter:GoodsKindsCtr? = nil
    public lazy var filter:GoodsKindsCtr = { [unowned self] in
        if let ft = self._filter{
            return ft
        }
        let ctr = GoodsKindsCtr()
        self._filter = ctr
        guard let ViewCtr = self.delegate as? UIViewController else {
            return ctr
        }
        
        if let mo = ViewCtr as? MoAtrributeProtocol
        {
            //            print("=sssss=====ooo|\(mo.mo.detail)")
            ctr.mo.model = mo.mo.detail
        }
        return ctr
        }()
    
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return [Swidth/menus.count.cg_floatValue,bar_height]
    }
    
    
}

extension OrderMenu
{
    
    open class DescOrderKit: JoCollectionCell {
        let titleL = UILabel()
        let iconV = UIImageView()
        let touchBt = UIButton()
        
        override open func addLayoutRules() {
            let itemV = UIView()
            contentView.eelay = [
                [itemV,[ee.X.Y,[5,0]]],
                [touchBt,[ee.T.L.B.R]]
            ]
            itemV.eelay = [
                [iconV,[ee.T.L.B],.<"40",.<40],
                [titleL,[ee.R],[iconV,ee.R,ee.L,4],[ee.Y]],
            ]
            touchBt.addTarget(self, action: #selector(touchAction), for: .touchUpInside)
            _ = titleL.ui.font12.cl_666
        }
        
        open override func mo_model_reload() {
            titleL.text = mo.model["name",""]
            updateImg()
            let color = (mo.model[FK.selected,FK.NO] == FK.YES) ? UIColor(shex:UIColor.main_hex) : UIColor(shex: "#999")
            
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(TimeInterval(0.2))
            UIView.setAnimationCurve(.easeIn)
            titleL.textColor = color
            UIView.commitAnimations()
            
        }
        
        @objc open func touchAction()
        {
            if mo.model[FK.selected,FK.NO] == FK.YES
            {
            }
            else{
                active(ID: "change")
            }
        }
        
        open func updateImg() {
            let color = (mo.model[FK.selected,FK.NO] == FK.YES) ? UIColor(shex:UIColor.main_hex) : UIColor(shex: "#999")
            iconV.image = DataNode<UIImage>.path(node: "icon", mo.model)?.rt_tintedImage(with: color)
        }
    }
    
    class FullOrderKit: DescOrderKit {
        override func touchAction()
        {
            mo.model[FK.selected] = FK.YES
            let order = (mo.model[FK.value,"desc"] == "asc") ? "desc" : "asc"
            mo.model[FK.value] = order
            active(ID: "change_price_order")
        }
        
        func changeOrder(animated:Bool) {
            
            let degree = (mo.model[FK.value,"desc"] == "asc") ? 180 : 0
            
            
            if animated
            {
                UIView.beginAnimations(nil, context: nil)
                UIView.setAnimationDuration(TimeInterval(0.2))
                UIView.setAnimationCurve(.easeIn)
                iconV.degree = Double(degree)
                UIView.commitAnimations()
                
            }
            else{
                iconV.degree = Double(degree)
            }
        }
        
        override func updateImg() {
            let img = (mo.model[FK.value,"desc"] == "asc") ? DataNode<UIImage>.path(node: "icon_asc", mo.model) : DataNode<UIImage>.path(node: "icon_desc", mo.model)
            let color = (mo.model[FK.selected,FK.NO] == FK.YES) ? UIColor(shex:UIColor.main_hex) : UIColor(shex: "#999")
            iconV.image = img?.rt_tintedImage(with: color)
        }
        override func mo_model_reload() {
            
            super.mo_model_reload()
            if mo.model[FK.selected,FK.NO] == FK.YES
            {
                changeOrder(animated: true)
            }
            
            
        }
    }
    
    class FilterKit:DescOrderKit{
        override func touchAction()
        {
            active(ID: "chose_filter")
        }
        
    }
    
    
    
}





